package de.tuberlin.swt.prog2.httpserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class HttpHelper {
	private static final String[] HEADERS = {"Server: PROG2/0.1", "Connection: close", "Content-Type: text/html; charset=UTF-8"};

	private static final String LINE_END = "\r\n";

	/**
	 * Hidden constructor as there are only static functions and instantiation
	 * is consequently useless.
	 */
	private HttpHelper() {
	}

	public static void handleRequest(BufferedReader input, BufferedWriter output, final String requestLine)
			throws IOException, FileNotFoundException {
		
		// TODO: validate requests
		
		// TODO: handle valid requests
	}

	private static void handleHttpHeadRequest(BufferedReader input, BufferedWriter output, final String requestedUri)
			throws IOException {
		
		// TODO: handle valid head request
	}
	
	private static void handleHttpGetRequest(BufferedReader input, BufferedWriter output, final String requestedUri) 
			throws IOException, FileNotFoundException {
		
		// TODO: handle valid get request
	}
	
	private static void handleHttpPostRequest(BufferedReader input, BufferedWriter output, final String requestedUri) 
			throws IOException, FileNotFoundException {
		
		// TODO: handle valid post request
	}



	private static void sendHeader(final BufferedWriter output, final int status, final String description, final String[] headerLines) 
			throws IOException {
		
		output.write("HTTP/1.1 " + status + " " + description + LINE_END);
		for (String header : headerLines) {
			output.write(header + LINE_END);
		}
		output.write(LINE_END);
	}

	/**
	 * Simple wrapper for System.out.println to add some formatting.
	 * 
	 * @param string the string to write to the log
	 */
	private static void log(final String string) {
		System.out.println("  " + string);
	}

	/**
	 * Reads the content of the given file and writes it to the given output stream.
	 * 
	 * @param output the stream to write to
	 * @param file the file to read from
	 * 
	 * @throws FileNotFoundException if the file was not found
	 * @throws IOException if an input or output exception occured
	 */
	private static void sendFile(final BufferedWriter output, final File file)
			throws FileNotFoundException, IOException {
		
		BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
		String fileLine = fileReader.readLine();
		while (fileLine != null) {
			output.write(fileLine + LINE_END);
			fileLine = fileReader.readLine();
		}
	}
}
